
import requests
import json
import datetime
import random
import time
import threading

class getTongHuaShunData(threading.Thread):
    def __init__(self,strategyName,cookie,recordTxtName):
        threading.Thread.__init__(self)
        self.strategyName = strategyName
        self.cookie = cookie
        self.recordTxtName = recordTxtName
        
    def run(self):
        print('开始')
          ############### 变量设置
        dailyUpUrl = dailyUp_pro
        tongHuaShunV = self.cookie  
        ###############
        record = open(self.recordTxtName,'w',encoding='utf-8')
        todayDate = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")

        uploadJson = {}
        uploadJson['uploadDate'] = todayDate
        uploadData = []

        f = open(self.strategyName,encoding="utf-8")
        
        for line in f.readlines():
            if line != '':
                sleepTIme = random.randint(5,10)
                print('sleepTime: %s' %sleepTIme)
                arr = line.split(' ')
                strategyId = int(arr[0])
                strategyName = arr[1]
                print(strategyId,strategyName,'===========   start' ) 

                stockCodes = getDatasFromTongHua(strategyName=strategyName,record = record,tongHuaShunV = tongHuaShunV,strategyId =strategyId )
                stockInfos = {"strategyId":strategyId,"stockCodes":stockCodes}
                uploadData.append(stockInfos)

                time.sleep(sleepTIme)
                print(strategyId,strategyName,'===========   end' ) 

        f.close()
        uploadJson['data'] = uploadData
        jsonBoday = json.dumps(uploadJson)
        record.write(jsonBoday)
        dailyUpResponse = requests.request("POST", dailyUpUrl, headers=dailyUp_headers, data=jsonBoday)
        print(dailyUpResponse.text)
        record.write('\n')
        record.write(dailyUpResponse.text)
        record.close()
        print('结束')


## dailyUp数据
dailyUp_dev = "https://engraveshine.cn/dev/dailyup/daily/stock/upload"

dailyUp_pro = "https://engraveshine.cn/dailyup/daily/stock/upload"

dailyUp_headers = {
    'adminToken': 'dingguanghui888',
     'Content-Type': 'application/json'
}

## 同花顺数据
cookies = {
    'c_f_f': 'isshow',
    # 'ta_random_userid': 'axembwyd0s',
    'WafStatus': '0',
    'cid': 'a471bb621b939738d1a18a6216818afd1649038464',
    'ComputerID': 'a471bb621b939738d1a18a6216818afd1649038464',
    'other_uid': 'Ths_iwencai_Xuangu_bi2i6b1i0ob9kzurgjwk1avlu56uakf1',
    'user': 'MDpTdW5EYXk1S1g6Ok5vbmU6NTAwOjQ2OTg4MjI1OTo3LDExMTExMTExMTExLDQwOzQ0LDExLDQwOzYsMSw0MDs1LDEsNDA7MSwxMDEsNDA7MiwxLDQwOzMsMSw0MDs1LDEsNDA7OCwwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMSw0MDsxMDIsMSw0MDoyNDo6OjQ1OTg4MjI1OToxNjQ5MDM5MjUzOjo6MTUzNDMwNzg4MDoyNjc4NDAwOjA6MTdmNmY2ZTJiZDA3NjZmZDQ0Y2YwYWJlNjYyZTlkNTMxOmRlZmF1bHRfNDox',
    'userid': '459882259',
    'u_name': 'SunDay5KX',
    'escapename': 'SunDay5KX',
    # 'ticket': '09c199e09ef920020285c471b544e5e8',
    'user_status': '0',
    # 'utk': 'b0ae9b940eb41cb2ff9e526c35c2174e',
    # 'PHPSESSID': '5535d42fcb4d6f6faf612ecc6c31c177',
    'v': 'A-QOtqucWjyuQK7weHLcgxh-tenUfQjRyqCcK_4Fcmly-45XJo3YdxqxbL5N',
}

headers = {
    'Host': 'www.iwencai.com',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'X-Requested-With': 'XMLHttpRequest',
    # 'hexin-v': 'A4pghHEa3K83j1ADTqma0aLQ23suew4_APiCTRTDNItoliCl_Ate5dCP0oDn',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.12 Safari/537.36',
    'Referer': 'http://www.iwencai.com/stockpick/search?typed=0&preParams=&ts=1&f=1&qs=result_original&selfsectsn=&querytype=stock&searchfilter=&tid=stockpick&w=%E8%BF%9E%E7%BB%AD3%E6%9C%88%E4%B8%8A%E6%B6%A8%3B%E6%B2%AA%E6%B7%B1A%E8%82%A1%3B%E4%B8%8A%E5%B8%82%E5%A4%A7%E4%BA%8E300%E5%A4%A9%3B&queryarea=',
    'Accept-Language': 'en-US,en;q=0.9',
    # Requests sorts cookies= alphabetically
    # 'Cookie': 'c_f_f=isshow; ta_random_userid=axembwyd0s; WafStatus=0; cid=a471bb621b939738d1a18a6216818afd1649038464; ComputerID=a471bb621b939738d1a18a6216818afd1649038464; other_uid=Ths_iwencai_Xuangu_bi2i6b1i0ob9kzurgjwk1avlu56uakf1; user=MDpTdW5EYXk1S1g6Ok5vbmU6NTAwOjQ2OTg4MjI1OTo3LDExMTExMTExMTExLDQwOzQ0LDExLDQwOzYsMSw0MDs1LDEsNDA7MSwxMDEsNDA7MiwxLDQwOzMsMSw0MDs1LDEsNDA7OCwwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMSw0MDsxMDIsMSw0MDoyNDo6OjQ1OTg4MjI1OToxNjQ5MDM5MjUzOjo6MTUzNDMwNzg4MDoyNjc4NDAwOjA6MTdmNmY2ZTJiZDA3NjZmZDQ0Y2YwYWJlNjYyZTlkNTMxOmRlZmF1bHRfNDox; userid=459882259; u_name=SunDay5KX; escapename=SunDay5KX; ticket=09c199e09ef920020285c471b544e5e8; user_status=0; utk=b0ae9b940eb41cb2ff9e526c35c2174e; PHPSESSID=5535d42fcb4d6f6faf612ecc6c31c177; v=A4pghHEa3K83j1ADTqma0aLQ23suew4_APiCTRTDNItoliCl_Ate5dCP0oDn',
}

params = {
    'typed': '0',
    'preParams': '',
    'ts': '1',
    'f': '1',
    'qs': 'result_original',
    'selfsectsn': '',
    'querytype': 'stock',
    'searchfilter': '',
    'tid': 'stockpick',
    'w': '连续3月上涨;沪深A股;上市大于300天;',
    'queryarea': '',
}


# response = requests.get('http://www.iwencai.com/stockpick/load-data', params=params, cookies=cookies, headers=headers)
# print(response.text)
# c = json.loads(response.text)['data']['result']['result']
# print('--------')
# print(c)
def getDatasFromTongHua(strategyName,record,tongHuaShunV,strategyId ):
    params['w'] = strategyName
    rs = []
    cookies['v'] = tongHuaShunV

    response = requests.get('http://www.iwencai.com/stockpick/load-data', params=params, cookies=cookies, headers=headers)

    print(response.status_code)
    if response.status_code != 200:
        record.write(str(strategyId) + ' ' +strategyName)
        record.write(str(response.status_code) + '----' + response.text)
        record.write('\n')
    else:
        c = json.loads(response.text)['data']['result']['result']
        print('数据长度:',str(len(c)),'\n')
        for i in c:
            # rs.append('"' + i[0][0:6] + '"')
            rs.append(i[0][0:6])
    return rs

if __name__ == "__main__":
    cookies = ['',
        '',
        ''
    ]

    for i in range(1,4):
        strategyName = 'strategy' + str(i) + '.txt'
        recordTxt = 'record' + str(i) + '.txt'
        t = getTongHuaShunData(strategyName,cookies[i-1],recordTxt)
        t.start()
        print(i)
  